import Vue from 'vue';
import Router from 'vue-router';
import layout from '@/components/layout/layout';
import login from '@/components/login/login';
import index from '@/components/contents/index/index';
import role from '@/components/contents/role/role';
import user from '@/components/contents/user/user';
import project from '@/components/contents/project/project';
import product from '@/components/contents/product/product';
import store from '@/vuex/store';
Vue.use(Router);

const router = new Router({
    routes: [
        {
            path: '/',
            name: 'layout',
            component: layout,
            meta: { requireAuth: true }, // 添加该字段，表示进入这个路由是需要登录的
            redirect: 'index', // 默认路由
            children: [
                { path: 'index', name: 'index', component: index },
                { path: 'role', name: 'role', component: role },
                { path: 'user', name: 'user', component: user },
                { path: 'project', name: 'project', component: project },
                { path: 'product', name: 'product', component: product }
            ]
        },
        {
            path: '/login',
            name: 'login',
            component: login
        },
        {
            path: '*',
            redirect: {path: '/'}
        },
        {
            path: '', 
            redirect: {path: '/'}
        }//设置默认路径
    ]
});
// 路由守卫
router.beforeEach((to, from, next) => {
    if (to.matched[0].meta.requireAuth) {  // 判断该路由是否需要登录权限
        if (store.state.token == true) {  // 通过vuex state获取当前的token是否存在
            next();
        }
        else {
            next({
                path: '/login',
                query: { redirect: to.fullPath }  // 将跳转的路由path作为参数，登录成功后跳转到该路由
            })
        }
    }
    else {
        next();
    }
})

export default router;